/******************************************************************************
 * Product: Adempiere ERP & CRM Smart Business Solution                       *
 * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.                *
 * This program is free software; you can redistribute it and/or modify it    *
 * under the terms version 2 of the GNU General Public License as published   *
 * by the Free Software Foundation. This program is distributed in the hope   *
 * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           *
 * See the GNU General Public License for more details.                       *
 * You should have received a copy of the GNU General Public License along    *
 * with this program; if not, write to the Free Software Foundation, Inc.,    *
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.                     *
 * For the text or an alternative of this public license, you may reach us    *
 * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA        *
 * or via info@compiere.org or http://www.compiere.org/license.html           *
 *****************************************************************************/
package org.compiere.model;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

import org.inspire.model.*;
import java.math.RoundingMode;

/**
 * 	Payment Allocate Model
 *	
 *  @author Jorg Janke
 *  @version $Id: MPaymentAllocate.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
 */
public class MPaymentAllocate extends X_C_PaymentAllocate
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 2894385378672375131L;

	/**
	 * 	Get active Payment Allocation of Payment
	 *	@param parent payment
	 *	@return array of allocations
	 */
	public static MPaymentAllocate[] get (MPayment parent)
	{
		final String whereClause = "C_Payment_ID=?";
		Query query = MTable.get(parent.getCtx(), Table_ID).createQuery(whereClause, parent.get_TrxName());
		query.setParameters(parent.getC_Payment_ID()).setOnlyActiveRecords(true);
		List<MPaymentAllocate> list = query.list();
		return list.toArray(new MPaymentAllocate[list.size()]);
	}	//	get
	
	/**************************************************************************
	 * 	Standard Constructor
	 *	@param ctx context
	 *	@param C_PaymentAllocate_ID id
	 *	@param trxName trx
	 */
	public MPaymentAllocate (Properties ctx, int C_PaymentAllocate_ID, String trxName)
	{
		super (ctx, C_PaymentAllocate_ID, trxName);
		if (C_PaymentAllocate_ID == 0)
		{
		//	setC_Payment_ID (0);	//	Parent
		//	setC_Invoice_ID (0);
			setAmount (Env.ZERO);
			setDiscountAmt (Env.ZERO);
			setOverUnderAmt (Env.ZERO);
			setWriteOffAmt (Env.ZERO);
			setInvoiceAmt(Env.ZERO);
		}	
	}	//	MPaymentAllocate

	/**	The Invoice				*/
	private MInvoice	m_invoice = null;
	
	/**
	 * 	Load Cosntructor
	 *	@param ctx context
	 *	@param rs result set
	 *	@param trxName trx
	 */
	public MPaymentAllocate (Properties ctx, ResultSet rs, String trxName)
	{
		super (ctx, rs, trxName);
	}	//	MPaymentAllocate
	
	/**
	 * 	Set C_Invoice_ID
	 *	@param C_Invoice_ID id
	 */
	public void setC_Invoice_ID (int C_Invoice_ID)
	{
		super.setC_Invoice_ID (C_Invoice_ID);
		m_invoice = null;
	}	//	setC_Invoice_ID
	
	/**
	 * 	Get Invoice
	 *	@return invoice
	 */
	public MInvoice getInvoice()
	{
		if (m_invoice == null && getC_Invoice_ID() != 0)
			m_invoice = new MInvoice(getCtx(), getC_Invoice_ID(), get_TrxName());
		return m_invoice;
	}	//	getInvoice
	
	/**
	 * 	Get BPartner of Invoice
	 *	@return bp
	 */
	public int getC_BPartner_ID()
	{
		if (m_invoice == null)
			getInvoice();
		if (m_invoice == null)
			return 0;
		return m_invoice.getC_BPartner_ID();
	}	//	getC_BPartner_ID
	
	
	/**
	 * 	Before Save
	 *	@param newRecord new
	 *	@return true
	 */
	protected boolean beforeSave (boolean newRecord)
	{
		MPayment payment = new MPayment (getCtx(), getC_Payment_ID(), get_TrxName());
		if ((newRecord || is_ValueChanged("C_Invoice_ID"))
			&& (payment.getC_Charge_ID() != 0 
				|| payment.getC_Invoice_ID() != 0 
				|| payment.getC_Order_ID() != 0))
		{
			log.saveError("PaymentIsAllocated", "");
			return false;
		}
		
		BigDecimal check = getAmount()
			.add(getDiscountAmt())
			.add(getWriteOffAmt())
			.add(getOverUnderAmt());
		if (check.compareTo(getInvoiceAmt()) != 0)
		{
			log.saveError("Error", Msg.parseTranslation(getCtx(), 
				"@InvoiceAmt@(" + getInvoiceAmt()
				+ ") <> @Totals@(" + check + ")"));
			return false;
		}
		
		//	Org
		if (newRecord || is_ValueChanged("C_Invoice_ID"))
		{
			getInvoice();
			if (m_invoice != null)
				setAD_Org_ID(m_invoice.getAD_Org_ID());
		}
		
		return true;
	}	//	beforeSave
	
	protected boolean UpdateHeader (boolean newRecord, boolean success)
	{
		int PaymentId = getC_Payment_ID();

		String sql = "Select NVL(Sum(Amount),0), nvl(Sum(Taxamt),0), nvl(sum(DiscountAmt),0) " +
				"From C_Paymentallocate Cp " +
				"Where  Cp.C_Payment_Id = ?";			//			#4
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			pstmt = DB.prepareStatement(sql, get_TrxName());
			
			pstmt.setInt(1, PaymentId);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				BigDecimal PaymentTotal = rs.getBigDecimal(1);		//	Total Payment Amount
				BigDecimal TaxTotal = rs.getBigDecimal(2);		//	Total Tax Amount
				BigDecimal TaxDiscount = rs.getBigDecimal(3);		//	Total discount Amount
				
				String SQLUpdate;
				SQLUpdate = "UPDATE C_Payment " +
						"SET Payamt = " + PaymentTotal + 
						", Taxamt = " + TaxTotal +
						", DiscountAmt = " + TaxDiscount +
						" WHERE " +
						"C_Payment_Id = " + PaymentId;
				
				DB.executeUpdate(SQLUpdate, get_TrxName());

			}
		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, sql, e);
			return false;
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}				
		
		return success;
	}
	
	
	protected boolean InsertTaxLines()
	{
		
		//added by ARH to handle the code in case of empty taxID
		if(get_Value("C_Tax_Id") == null && getC_PaymentAllocate_ID() != 0)
		{ 
			//Delete old child entries
			
			String sqlDelete = "DELETE Ins_PaymentTax " +
					"WHERE C_PaymentAllocate_ID=" + getC_PaymentAllocate_ID();
			DB.executeUpdate(sqlDelete, get_TrxName());
			
			return false;
		}else if (get_Value("C_Tax_Id") == null)
		{ 
			return false;
		} 
		
		
		
		
		int TaxId = (Integer) get_Value("C_Tax_Id");
		BigDecimal TaxAmt = (BigDecimal) get_Value("TaxAmt") ;

		//Delete old child entries
		
		String sqlDelete = "DELETE Ins_PaymentTax " +
				"WHERE C_PaymentAllocate_ID=" + getC_PaymentAllocate_ID();
		DB.executeUpdate(sqlDelete, get_TrxName());

		
		//Exit if TaxAmt is 0
		if (TaxAmt.equals(Env.ZERO))
			return true;
		
		String sql = "SELECT COUNT(*) FROM C_TAX " +
				"WHERE Parent_Tax_Id = ?";
		int IsParent = DB.getSQLValue(get_TrxName(), sql, TaxId);

		

		if (IsParent == 0) // It has No Childs
		{
			//Inserting new records
			X_INS_PaymentTax PaymentTax = new X_INS_PaymentTax(getCtx(), null, get_TrxName());
			PaymentTax.setC_Tax_ID(TaxId);
			PaymentTax.setAmount( TaxAmt );
			PaymentTax.setC_Payment_ID( getC_Payment_ID() );
			PaymentTax.setC_PaymentAllocate_ID( getC_PaymentAllocate_ID() ); 
			PaymentTax.save();
		}
		
		else // Tax is Parent
		{
			String sqlParent = "Select  T.C_Tax_Id, T.Rate " +
							"From C_Tax T " +
							"Where Parent_Tax_Id=?";

			PreparedStatement pstmt = null;
			ResultSet rs = null;
			try
			{
				pstmt = DB.prepareStatement(sqlParent, get_TrxName());
				
				pstmt.setInt(1, TaxId);
				rs = pstmt.executeQuery();
				while (rs.next())
				{
					//BigDecimal PaymentTotal = rs.getBigDecimal(1);		//	Total Payment Amount
					MTax m_tax = new MTax(getCtx(), TaxId, get_TrxName());
					BigDecimal TotalTaxPercent = m_tax.getRate();
					BigDecimal ThisTaxRate	= (BigDecimal) rs.getBigDecimal(2);
					BigDecimal ThisTaxRatio = ThisTaxRate.divide(TotalTaxPercent, 2, RoundingMode.HALF_UP);
					BigDecimal ThisTaxAmount = TaxAmt.multiply(ThisTaxRatio);

					
					//Inserting new records
					X_INS_PaymentTax PaymentTax = new X_INS_PaymentTax(getCtx(), null, get_TrxName());
					PaymentTax.setC_Tax_ID(rs.getInt(1));
					PaymentTax.setAmount( ThisTaxAmount );
					PaymentTax.setC_Payment_ID( getC_Payment_ID() );
					PaymentTax.setC_PaymentAllocate_ID( getC_PaymentAllocate_ID() ); 
					PaymentTax.save();

				}
			}
			catch (SQLException e)
			{
				log.log(Level.SEVERE, sqlParent, e);
				return false;
			}
			finally
			{
				DB.close(rs, pstmt);
				rs = null; pstmt = null;
			}							
			
		}
		return true;
		
	}
	
	protected boolean afterSave (boolean newRecord, boolean success)
	{

		UpdateHeader (newRecord, success);
		
		InsertTaxLines();
		
		return success;
	}	//afterSave

	
	protected boolean afterDelete (boolean success)
	{
		return UpdateHeader (false, success); //Same functionality in case a record is deleted which is used on insert/update

	}

	
}	//	MPaymentAllocate
